import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
const router = new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/home'
    },

    // 首页
    {
      path: '/home',
      component: () => import('@/views/Home'),
      meta: { showFooter: true } // 显示底部导航组件
    },

    // 用户页
    {
      path: '/user',
      component: () => import('@/views/User'),
      meta: { showFooter: true } // 显示底部导航组件
    },

    // 设置页面
    {
      path: '/shezhi',
      component: () => import('@/views/User/Shezhi'),
      meta: { showFooter: false }
    },

    // 登录页
    {
      path: '/login',
      component: () => import('@/views/login/login'),
      meta: { showFooter: false }
    }
  ]
})

// 定义要跳转的路由
const pathArr = ['/', '/home', '/user', '/shezhi']

// 路由前置守卫
router.beforeEach((to, from, next) => {
  // 获取内存中的userToken
  const userToken = localStorage.getItem('userToken')
  if (userToken) {
    if (to.path === '/login') {
      next('/home')
    } else {
      next()
    }
  } else {
    //  如果要跳转的路由在pathArr中
    if (pathArr.indexOf(to.path) !== -1) {
      next('/login')
    } else {
      next()
    }
  }
})

export default router
